package com.cn.common.consumer;

import com.cn.common.ClientInfo;
import io.netty.channel.Channel;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ConsumerGroupInfo {

    private String consumerGroup;
    private ConcurrentMap<Channel, ClientChannelInfo> clientChannelTabls = new ConcurrentHashMap<>();

    private long lastUpdateTime;

    public ConsumerGroupInfo() {
    }

    public ConsumerGroupInfo(String consumerGroup, ConcurrentMap<Channel, ClientChannelInfo> clientChannelTabls) {
        this.consumerGroup = consumerGroup;
        this.clientChannelTabls = clientChannelTabls;
    }

    public void updateChannel(Channel channel, ClientInfo clientInfo) {
        ClientChannelInfo channelInfo = this.clientChannelTabls.get(channel);
        if (channelInfo == null) {
            channelInfo = new ClientChannelInfo().setChannel(channel).setClientId(clientInfo.getCientId());
            this.clientChannelTabls.putIfAbsent(channel, channelInfo);
        } else {
            if (!channelInfo.getClientId().equals(clientInfo.getCientId())) {
                channelInfo.setClientId(clientInfo.getCientId());
            }
            channelInfo.setLastUpdateTime(System.currentTimeMillis());
        }
    }


    public String getConsumerGroup() {
        return consumerGroup;
    }

    public ConsumerGroupInfo setConsumerGroup(String consumerGroup) {
        this.consumerGroup = consumerGroup;
        return this;
    }

    public ConcurrentMap<Channel, ClientChannelInfo> getClientChannelTabls() {
        return clientChannelTabls;
    }

    public ConsumerGroupInfo setClientChannelTabls(ConcurrentMap<Channel, ClientChannelInfo> clientChannelTabls) {
        this.clientChannelTabls = clientChannelTabls;
        return this;
    }

    public long getLastUpdateTime() {
        return lastUpdateTime;
    }

    public ConsumerGroupInfo setLastUpdateTime(long lastUpdateTime) {
        this.lastUpdateTime = lastUpdateTime;
        return this;
    }

    @Override
    public String toString() {
        return "ConsumerGroupInfo{" +
                "consumerGroup='" + consumerGroup + '\'' +
                ", clientChannelTabls=" + clientChannelTabls +
                ", lastUpdateTime=" + lastUpdateTime +
                '}';
    }
}
